package fun.lifepoem.pattern.cor;

import fun.lifepoem.pattern.cor.exception.CorException;

import java.util.ArrayList;
import java.util.List;

public class ChainExecutor {

    private List<Command> commands;

    private BaseContext context;

    public static ChainExecutor builder() {
        ChainExecutor chainExecutor = new ChainExecutor();
        chainExecutor.commands = new ArrayList<>();
        return chainExecutor;
    }

    public ChainExecutor setContext(BaseContext context) {
        this.context = context;
        return this;
    }

    public ChainExecutor addCommand(Command command) {
        commands.add(command);
        return this;
    }


    /**
     * 责任链执行器
     *
     * @throws CorException
     */
    public boolean execute() throws CorException {
        for (Command command : commands) {
            boolean actionResult = command.doAction(context);
            if (!actionResult) {
                return false;
            }
        }
        return true;
    }
}
